package ma.cdm.compteRendu.dao;
// default package


import static org.hibernate.criterion.Example.create;

import java.util.Date;
import java.util.List;

import ma.cdm.compteRendu.bo.CompteRendu;

import org.apache.axis.utils.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.transaction.annotation.Transactional;

/**
 	* A data access object (DAO) providing persistence and search support for CompteRendu entities.
 			* Transaction control of the save(), update() and delete() operations 
		can directly support Spring container-managed transactions or they can be augmented	to handle user-managed Spring transactions. 
		Each of these methods provides additional information for how to configure it for the desired type of transaction control. 	
	 * @see .CompteRendu
  * @author Limouri Anouar 
 */
    @Transactional   
public class CompteRenduDAO  {
	     private static final Logger log = LoggerFactory.getLogger(CompteRenduDAO.class);
		//property constants
	public static final String OBJETCOMPTERENDU = "objetcompterendu";



    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory){
       this.sessionFactory = sessionFactory;
    }

    private Session getCurrentSession(){
     return sessionFactory.getCurrentSession(); 
    }
	protected void initDao() {
		//do nothing
	}
    
    public void save(CompteRendu transientInstance) {
        log.debug("saving CompteRendu instance");
        try {
            getCurrentSession().save(transientInstance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }
    
	public void delete(CompteRendu persistentInstance) {
        log.debug("deleting CompteRendu instance");
        try {
            getCurrentSession().delete(persistentInstance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }
    
    public CompteRendu findById( java.lang.Long id) {
        log.debug("getting CompteRendu instance with id: " + id);
        try {
            CompteRendu instance = (CompteRendu) getCurrentSession()
                    .get(CompteRendu.class, id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
    
    
    @SuppressWarnings("unchecked")
	public List<CompteRendu> findByExample(CompteRendu instance) {
        log.debug("finding CompteRendu instance by example");
        try {
            List<CompteRendu> results = (List<CompteRendu>) getCurrentSession() .createCriteria(CompteRendu.class).add( create(instance) ).list();
            log.debug("find by example successful, result size: " + results.size());
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }    
    
   
    

    
    public void deleteCompteRenduDependencies(Long reportId)
    {
    	try { 
    		//supprimer les responsables aux points
	   		 String queryResponsable=  "delete from responsablepoint where IDDETAILPOINT in (select dp.ID  from detailpoint dp where IDSUIVI in(select sw.ID from suivipoint sw where  sw.IDCOMPTERENDU= ?))";
	   		 Query queryObjectResponsable = getCurrentSession().createSQLQuery(queryResponsable);
	   		queryObjectResponsable.setParameter(0, reportId);
	   		queryObjectResponsable.executeUpdate();	         
   		 
    		//supprimer les details des points
    		 String queryDetail =  "delete from detailpoint where IDSUIVI in(select sw.ID from suivipoint sw where  sw.IDCOMPTERENDU= ? )";
    		 Query queryObjectDetail = getCurrentSession().createSQLQuery(queryDetail);
    		 queryObjectDetail.setParameter(0, reportId);
    		 queryObjectDetail.executeUpdate();	         
	         
    		// supprimer les liaison du point
	         String queryPoint = "delete from suivipoint where idcompterendu= ? ";
	         Query queryObjectPoint = getCurrentSession().createSQLQuery(queryPoint);
	         queryObjectPoint.setParameter(0, reportId);
	         queryObjectPoint.executeUpdate();
	         
	         
	      // supprimer les liaison aux personnes externe
	         String queryExterne = "delete from participantexterne where idcompterendu= ? ";
	         Query queryObjectExterne = getCurrentSession().createSQLQuery(queryExterne);
	         queryObjectExterne.setParameter(0, reportId);
	         queryObjectExterne.executeUpdate();
	         
	      // supprimer les liaison aux personnes internes
	         String queryInterne = "delete from participantinterne where idcompterendu= ? ";
	         Query queryObjectInternet = getCurrentSession().createSQLQuery(queryInterne);
	         queryObjectInternet.setParameter(0, reportId);
	         queryObjectInternet.executeUpdate();
	         
	      // supprimer les liaison aux membres present         
	         String queryPresent = "delete from membrepresent where idcompterendu= ? ";
	         Query queryObjectPresent = getCurrentSession().createSQLQuery(queryPresent);
	         queryObjectPresent.setParameter(0, reportId);
	         queryObjectPresent.executeUpdate();
	      } catch (RuntimeException re) {
	         log.error(" deleteCompteRenduDependencies by rapportId failed", re);
	         throw re;
	      }
    }
    @SuppressWarnings("unchecked")
	public List<CompteRendu> getCompteRenduByComite(Long comiteId, int maxResults)
    {
    	Criteria criteria = getCurrentSession().createCriteria(CompteRendu.class);
        criteria.add(Restrictions.eq("comite.idcomite", comiteId));
        criteria.setMaxResults(maxResults);
        return criteria.list();
    }
    @SuppressWarnings("unchecked")
	public List<CompteRendu> findByProperty(String propertyName, Object value) {
      log.debug("finding CompteRendu instance with property: " + propertyName
            + ", value: " + value);
      try {
         String queryString = "from CompteRendu as model where model." 
         						+ propertyName + "= ?";
         Query queryObject = getCurrentSession().createQuery(queryString);
		 queryObject.setParameter(0, value);
		 return queryObject.list();
      } catch (RuntimeException re) {
         log.error("find by property name failed", re);
         throw re;
      }
	}

	public List<CompteRendu> findByObjetcompterendu(Object objetcompterendu
	) {
		return findByProperty(OBJETCOMPTERENDU, objetcompterendu
		);
	}
	

	@SuppressWarnings("rawtypes")
	public List findAll() {
		log.debug("finding all CompteRendu instances");
		try {
			String queryString = "from CompteRendu";
	         Query queryObject = getCurrentSession().createQuery(queryString);
			 return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
    public CompteRendu merge(CompteRendu detachedInstance) {
        log.debug("merging CompteRendu instance");
        try {
            CompteRendu result = (CompteRendu) getCurrentSession()
                    .merge(detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public void attachDirty(CompteRendu instance) {
        log.debug("attaching dirty CompteRendu instance");
        try {
            getCurrentSession().saveOrUpdate(instance);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }
    
    public void attachClean(CompteRendu instance) {
        log.debug("attaching clean CompteRendu instance");
        try {
                      	getCurrentSession().buildLockRequest(LockOptions.NONE).lock(instance);
          	            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

	public static CompteRenduDAO getFromApplicationContext(ApplicationContext ctx) {
    	return (CompteRenduDAO) ctx.getBean("compteRenduDAO");
	}


	@SuppressWarnings("unchecked")
	public List<CompteRendu> rechercherCompteRendus(String objet,
	       Date dateDebut, Date dateFin, String[] pointTitle, Long comiteId, int maxResults) {
		
		try {
			Criteria criteria = getCurrentSession().createCriteria(CompteRendu.class);
			criteria.createAlias("suiviPoints", "suiv");
			criteria.createAlias("suiviPoints.point", "point");		
			criteria.add(Restrictions.eq("comite.idcomite", comiteId));
			criteria.setMaxResults(maxResults);
			if(objet != null && !StringUtils.isEmpty(objet.trim()))
			{
				 criteria.add(Restrictions.like("objetcompterendu", "%"+objet+"%"));
			}
			if(dateDebut != null)
			{
				criteria.add(Restrictions.ge("datereunion", dateDebut));
			}
			if(dateFin != null)
			{
				criteria.add(Restrictions.le("datereunion", dateFin));
			}
			if(pointTitle != null && pointTitle.length >0)
			{
				
				
				Disjunction orPoints =Restrictions.disjunction();
				for (String point : pointTitle) {
					if(point != null && !StringUtils.isEmpty(point.trim()))
					{
						orPoints.add(Restrictions.like("point.titrepoint", "%"+point+"%"));				
					}
				}			
				criteria.add(orPoints);
			}		
	        return criteria.list();
		} catch (Exception e) {
			return null;
		}
		
	}
}